<template>
  <a-layout style="">
    <!-- 内容 -->
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
    >
      <a-row :gutter=24>
        <a-col :span="8">
          <div class="tableEdit">
            <a-button type="primary" @click="add()" size="small">
              新增
            </a-button>
          </div>

          <a-table 
            v-if="categoryTree.length > 0"
            :columns="columns"
            :data-source="categoryTree"
            :pagination="false"
          :defaultExpandAllRows=true
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'name'">
                <a>
                  {{ record.name }}
                </a>
              </template>

              <template v-else-if="column.key === 'action'">
                <span>
                  <a-button type="primary" @click="edit(record)" size="small">
                    编辑
                  </a-button>
                  <a-divider type="vertical" />
                  <!-- 是否删除 -->
                  <a-popconfirm
                    :title="dynamicTitle"
                    ok-text="Yes"
                    cancel-text="No"
                    :loading="loading"
                    @confirm="handleDelete(record.id)"
                  >
                    <a-button type="primary" danger size="small">
                      删除
                    </a-button>
                  </a-popconfirm>
                </span>
              </template>
            </template>
          </a-table>
        </a-col>

        <a-col :span="16">
          <p>
            <a-form layout="inline">
              <a-form-item>
                <a-button type="primary" @click="handleSave()" size="small"
                  >保存</a-button
                >
              </a-form-item>
            </a-form>
          </p>

          <a-form
            :model="doc"
            layout="vertical"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="名称" />
            </a-form-item>

            <a-form-item>
              <a-tree-select
                v-model:value="doc.parent"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="选择父文档"
                allow-clear
                tree-default-expand-all
                :tree-data="treeSelectDate"
                :fieldNames="{
                  children: 'children',
                  label: 'name',
                  value: 'id',
                }"
              >
                <template #title="{ id: val, name }">
                  <b v-if="val === '文档一'" style="color: #08c">sss</b>
                  <template v-else>{{ name }}</template>
                </template>
              </a-tree-select>
            </a-form-item>

            <!-- <a-form-item>
            <div>
              <h2>{{ doc.name }}</h2>
              <div>
                <span>阅读数：{{ doc.viewCount }}</span> &nbsp; &nbsp;
                <span>点赞数：{{ doc.voteCount }}</span>
              </div>
              <a-divider style="height: 2px; background-color: #9999cc" />
            </div>
            <div class="wangeditor" :innerHTML="html"></div>
            <div class="vote-div">
              <a-button
                type="primary"
                shape="round"
                :size="'large'"
                @click="vote"
              >
                <template #icon
                  ><LikeOutlined /> &nbsp;点赞：{{ doc.voteCount }}
                </template>
              </a-button>
            </div>
          </a-form-item> -->

            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="顺序" />
            </a-form-item>

            <a-form-item>
              <div style="border: 1px solid #ccc">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 500px; overflow-y: hidden"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>


</template>

<script setup lang="ts">
import { useApi } from "@/api";
import { Tool } from "@/utils/tool";
import { message } from "ant-design-vue";
import { computed, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
import { useRoute } from "vue-router";
import { CategoryTree, EDoc, TreeSelectDate } from "../type";

const api = useApi();
const loading = ref(false);
const route = useRoute();

//表格的列
const columns = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "父文档",
    key: "parent",
    dataIndex: "parent",
  },
  {
    title: "顺序",
    dataIndex: "sort",
    key: "sort",
  },
  {
    title: "Action",
    key: "action",
  },
];

//------------------页面未加载-----------------


const treeSelectDate = ref<TreeSelectDate[]>([]);
//   获取文档数据
const docs = ref<EDoc[]>([
  {
    id: 0,
    ebookId: 0,
    parent: 0,
    name: "",
    sort: 0,
    viewCount: 0,
    voteCount: 0,
  },
]);
//保存需要的
const doc = ref<EDoc>({
  parent: 0,
  name: "",
  sort: 0,
  viewCount: 0,
  voteCount: 0,
});




const categoryTree =  ref<CategoryTree[]>([])

/**
 * 1.文档数据数据查询
 **/
const handleQuery = async (  ) => {
  //如果不清空数据,则编辑保存重新加载数据后,再点击编辑,数据会重复
  categoryTree.value = [];
  const data = await api.getSelectDocAll<EDoc[]>(route.query.ebookId as unknown as number);

  docs.value = data;
  categoryTree.value = Tool.array2Tree(docs.value, 0);
  treeSelectDate.value = Tool.array2Tree(docs.value, 0);

};

//内容加载
const handleQueryContent = async (id: number ) => {
  //如果不清空数据,则编辑保存重新加载数据后,再点击编辑,数据会重复
  
  const data = await api.getDocContent(id);
  valueHtml.value =data ;
};
onMounted(() => {
  handleQuery();

  dynamicTitle;


});

//-------------------页面加载完成-----------------

//一.头部

/**
 * 1.新增文档
 */
const add = () => {

  let ebookId = route.query.ebookId as unknown as number;
  doc.value = {
    ebookId,
    parent: 0,
    name: "",
    sort: 0,
    viewCount: 0,
    voteCount: 0,
  };

  // treeSelectDate.value = Tool.copy(categoryTree.value) || [];
  treeSelectDate.value.unshift({
    id: 0,
    name: "无",
  });
};

//-----------------二.表格------------------------




/**
 *  保存文档
 */
const handleSave = async () => {
  
  
  doc.value.content = valueHtml.value!
  console.log("点击保存", doc.value);
  await api.saveDocList(doc.value);

  message.success("文档保存成功");

  // 重新加载列表
  handleQuery();
};

/**
 * 将某节点及其子孙节点全部置为disabled
 */
const setDisable = (treeSelectData: TreeSelectDate[], id: number) => {
  // console.log(treeSelectData, id);
  // 遍历数组，即遍历某一层节点
  for (let i = 0; i < treeSelectData.length; i++) {
    const node = treeSelectData[i];
    if (node.id === id) {
      // 如果当前节点就是目标节点
      console.log("disabled", node);
      // 将目标节点设置为disabled
      node.disabled = true;

      // 遍历所有子节点，将所有子节点全部都加上disabled
      const children = node.children!;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          setDisable(children, children[j].id!);
        }
      }
    } else {
      // 如果当前节点不是目标节点，则到其子节点再找找看。
      const children = node.children!;
      if (Tool.isNotEmpty(children)) {
        setDisable(children, id);
      }
    }
  }
};

/**
 * 1.编辑
 */

const edit = (record: EDoc) => {
  doc.value = Tool.copy(record);
  if (doc.value.id) {
    handleQueryContent(doc.value.id);
  }

  //不能选择当前节点及所有子孙节点，作为父节点，会使树断开
  // treeSelectDate.value = Tool.copy(level1.value);

  setDisable(treeSelectDate.value, record.id!);
  //为选择树添加一个无字
  treeSelectDate.value.unshift({ id: 0, name: "无" });
};

const deleteIds: Array<string> = [];
const deleteNames = ref<string[]>([]);
const dynamicTitle = computed(() => {
  return `将删除：${deleteNames.value.join(",")}删除后不可恢复，确认删除？`;
});

/**
 *
 * 查找要删除的id
 */
const getDeleteIDs = (categoryTree: CategoryTree[], id: number) => {
  // console.log(treeSelectData, id);
  // 遍历数组，即遍历某一层节点
  for (let i = 0; i < categoryTree.length; i++) {
    const node = categoryTree[i];
    if (node.id === id) {
      // 如果当前节点就是目标节点
      console.log("disabled", node);

      deleteIds.push(id as unknown as string);
      deleteNames.value.push(node.name);

      console.log("deleteids", deleteIds);
      // 遍历所有子节点，将所有子节点全部都加上disabled
      const children = node.children!;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          getDeleteIDs(children, children[j].id!);
        }
      }
    } else {
      // 如果当前节点不是目标节点，则到其子节点再找找看。
      const children = node.children!;
      if (Tool.isNotEmpty(children)) {
        getDeleteIDs(children, id);
      }
    }
  }
};

/**
 * 2.删除
 */
const handleDelete = async (id: number) => {
  getDeleteIDs(categoryTree.value, id);
  loading.value = true;
  await api.deleteDoc(deleteIds);
  //ts中清空数组的方法， splice(0,leng),从第0个位置删到最后
  deleteIds.splice(0, deleteIds.length);
  handleQuery();
};

// -----------------------edit



import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

const mode = "default";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");



const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
.tableEdit {
  display: flex;
  flex-direction: row;
  justify-content: start;
}
.custom-search-input {
  width: 30%;
}
/* 富文本编辑器 */
#editor—wrapper {
  border: 1px solid #ccc;
  z-index: 100; /* 按需定义 */
}
#toolbar-container {
  border-bottom: 1px solid #ccc;
}
#editor-container {
  height: 500px;
}
</style>
